import React, { useState } from 'react';
import { Card, Form, Input, Button, message } from 'antd';
import { useNavigate } from 'react-router-dom';

export default function Password() {
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const navigate = useNavigate();

  const onFinish = async (values) => {
    setLoading(true);
    try {
      const { oldPassword, newPassword, confirmPassword } = values;
      if (!oldPassword || !newPassword || !confirmPassword) {
        throw new Error('请完整填写信息');
      }
      if (newPassword !== confirmPassword) {
        throw new Error('两次输入的新密码不一致');
      }
      // TODO: 调用后端修改密码接口
      await new Promise((res) => setTimeout(res, 600));
      message.success('密码修改成功');
      navigate('/main');
    } catch (e) {
      message.error(e.message || '修改失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Card title="修改密码" variant="borderless" style={{ maxWidth: 520 }}>
      <Form form={form} layout="vertical" onFinish={onFinish}>
        <Form.Item name="oldPassword" label="原密码" rules={[{ required: true, message: '请输入原密码' }]}>
          <Input.Password placeholder="原密码" />
        </Form.Item>
        <Form.Item name="newPassword" label="新密码" rules={[{ required: true, message: '请输入新密码' }]}>
          <Input.Password placeholder="新密码" />
        </Form.Item>
        <Form.Item name="confirmPassword" label="确认新密码" dependencies={["newPassword"]} rules={[{ required: true, message: '请再次输入新密码' }]}>
          <Input.Password placeholder="确认新密码" />
        </Form.Item>
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
          <Button onClick={() => navigate(-1)}>取消</Button>
          <Button type="primary" htmlType="submit" loading={loading}>提交</Button>
        </div>
      </Form>
    </Card>
  );
}